<template>
	<view>
        <uni-section title="datetime" type="line" subTitle="日期接口支持节假日、农历等，可用于农历生日提醒\nperiod依次是月经期、危险期、排卵日，=>可保存网址"></uni-section>
		<view @touchstart="start" @touchend="end">
			<uni-calendar ref="calendar" class="uni-calendar--hook" :lunar="info.lunar" :selected="info.selected" :calendarInfo="calendarInfo" :showMonth="info.showMonth" @change="change" @monthSwitch="monthSwitch" />
		</view>
        <text class="uni-text uni-padding-wrap">{{dayInfo}}</text>
		<view>
			<view class="uni-flex uni-row">
				<view class="text" style="-webkit-flex: 1;flex: 1;">
					<text class="uni-text">{{periodStart}}</text>
					<button class="mini-btn" type="plain" size="mini" @click="setPeriodStart(1)" title="设置当前选择日期为月经期开始日期">选择</button>
					<button class="mini-btn" type="plain" size="mini" @click="setPeriodStart(-1)" title="清除月经期开始日期">-</button>
				</view>
				<view class="text" style="-webkit-flex: 1;flex: 1;">
					<text class="uni-text">{{periodDays}}</text>
					<button class="mini-btn" type="plain" size="mini" @click="setPeriodDays(1)" title="动态调整月经周期天数+1">+</button>
					<button class="mini-btn" type="plain" size="mini" @click="setPeriodDays(-1)" title="动态调整月经周期天数-1">-</button>
					<button class="mini-btn" type="plain" size="mini" @click="setPeriodUrl()" title="点击后可添加网址到书签">=></button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
    var logserver = require('../../common/logserver.js');
    var logger = logserver.logger;
    
	export default {
		data() {
			return {
                dayInfo: '',
                calendarInfo: {},//缓存已请求的年月
                startData:{},
				periodStart:this.$route.query.start||uni.getStorageSync('apidemo.periodStart'),
				periodDays:Number(this.$route.query.days||uni.getStorageSync('apidemo.periodDays')||30),
				info: {
					lunar: true,
                    showMonth: true,
					selected: [],
				}
			}
		},
		onReady() {
            let date = this.$refs.calendar.cale.getDate();
			this.datetime(date.fullDate)
            logger.info('onReady index.vue');
			if(this.periodStart) this.period(date.fullDate.substr(0,7))
		},
		methods: {
			change(e) {
                this.datetime(e.fulldate) // e.lunar={"lYear":2021,"lMonth":11,"lDay":21,"Animal":"牛","IMonthCn":"冬月","IDayCn":"廿一","cYear":2021,"cMonth":12,"cDay":24,"gzYear":"辛丑","gzMonth":"庚子","gzDay":"丙午","isToday":false,"isLeap":false,"nWeek":5,"ncWeek":"星期五","isTerm":false,"Term":null,"astro":"魔羯座"}
			},
			monthSwitch(e) {
				let yearMonth = e.year+'-'+(e.month<10?'0'+e.month:e.month);
				this.period(yearMonth);
			},
            start(e){
                this.startData = e.changedTouches[0]
            },
            end(e){
                let offset = e.changedTouches[0].clientX - this.startData.clientX
                if(offset > 100){
                    console.log('上月')
                    this.$refs.calendar.pre()
                }else if(offset < -100){
                    console.log('下月')
                    this.$refs.calendar.next()
                }
            },
            dayinfo(data){
                this.dayInfo = data.ganzhi + data.shengxiao + '年，' + data.chinese
                let remark = data.remark || ''
                if(data.holiday) remark = data.holiday + (!data.remark ? '' : '('+data.remark+')')
                if(remark) this.dayInfo += '，' + remark;
                if(data.zodiac) this.dayInfo += '，' + data.zodiac;
            },
            datetime(day){
                let yearMonth = day.substring(0,7);
                if(this.calendarInfo[yearMonth] && this.calendarInfo[yearMonth][day]){
                    let data = this.calendarInfo[yearMonth][day];
                    this.dayinfo(data)
                    return;
                }
                this.calendar(yearMonth);
            },
            calendar(yearMonth){
                if(this.calendarInfo[yearMonth]) return;
                console.log('calendar: '+yearMonth)
                uni.request({
                    url: getApp().globalData.api.service+'/datetime/calendar.json',
                    dataType: 'application/json',
                    data: {
                        day: yearMonth+'-01'
                    },
                    success: (res) => {
                        if(res.data){
                           let data = JSON.parse(res.data)
                           this.calendarInfo[yearMonth] = data;
                           for(let day in data){
                               let info = data[day]
                               let select = (info.isweekend && info.isworkday) || (!info.isweekend && !info.isworkday) || info.isholiday;
                               //console.log(day+' select: '+select+','+JSON.stringify(info))
                               if(select){
                                   this.info.selected.push({
                                       date: day,
                                       info: info.isholiday ? '假' : (info.isworkday ? '班' : '休')
                                   })
                               }
                           }
						   this.period(yearMonth)
                        }
                    }
                })
            }
			,period(yearMonth) {
				let start=1,end=new Date(yearMonth.substr(0,4),yearMonth.substr(5,2),'00').getDate()
				let offset=!this.periodStart ? -32 : (new Date(yearMonth+'-01').getTime()-new Date(this.periodStart).getTime())/(24*60*60*1000);
				console.log('period ' + yearMonth + ' 1-' + end+' offset ' + offset)
				while(start<=end){
					let day = yearMonth + '-' + (start<10?'0':'') + start;
					let data = this.info.selected.find(item=>item.date===day);
					if(offset>=0) {
						let days = this.periodDays-offset%this.periodDays, color = '';
						if(days==14) color = 'blue';
						else if(days>=10&&days<=19) color = 'red';
						else if(offset%this.periodDays<3) color = 'magenta';
						if(!data) {
							if(color) this.info.selected.push({date:day,color:color});
						}else{
							if(color) data.color = color;
							else if(data.info) delete data.color;
							else this.info.selected.splice(this.info.selected.indexOf(data),1);
						}
					}else if(data){
						if(data.info) delete data.color;
						else this.info.selected.splice(this.info.selected.indexOf(data),1);
					}
					start += 1;
					offset += 1;
				}
			}
			,setPeriodStart(delta){
				if(delta>0){
					this.periodStart=this.$refs.calendar.nowDate.fullDate
					uni.setStorageSync('apidemo.periodStart', this.periodStart)
				}else{
					this.periodStart = null;
					uni.removeStorageSync('apidemo.periodStart')
				}
				this.period(this.$refs.calendar.nowDate.fullDate.substr(0,7))
			}
			,setPeriodDays(delta){
				if(this.periodDays<10) return;
				this.periodDays+=delta;
				if(this.periodStart) this.period(this.$refs.calendar.nowDate.fullDate.substr(0,7))
				uni.setStorageSync('apidemo.periodDays', this.periodDays)
			}
			,setPeriodUrl(){
				if(!this.periodStart) return;
				let href = location.href;
				href = href.lastIndexOf('?')==-1?href:href.substr(0,href.lastIndexOf('?'));
				href = href + '?start='+this.periodStart+'&days='+this.periodDays;
				location.href=href;
			}
		}
	}
</script>

<style>

</style>